//
//  SendMailHandler.m
//  IFlyUncaughtExceptions
//
//  Created by iflytek.com on 12-11-2.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SendMailHandler.h"
#import "SKPSMTPMessage.h"
#import "NSData+Base64Additions.h"

//#include <stdio.h>
#include <dirent.h>
//#include <sys/stat.h>

@interface SendMailHandler ()
// 获取dirPath路径下所有的文件路径
- (NSArray *)getAllFilePathBydirPath:(NSString *)dirPath;
// 移除某个文件
- (BOOL)removeFileByPath:(NSString *)filePath;
@end

@implementation SendMailHandler

@synthesize fromEmail = _fromEmail;
@synthesize password = _password;
@synthesize subject = _subject;
@synthesize relayHost = _relayHost;
@synthesize toEmail = _toEmail;
@synthesize messageDelegate = _messageDelegate;

#pragma mark -
#pragma mark 内存管理函数

- (void)dealloc
{
    [_filePathArray release];
    _filePathArray = nil;
    [_dirPathArray release];
    _dirPathArray = nil;
    [_mailParts release];
    _mailParts = nil;
    
    [_smtpMessage release];
    _smtpMessage = nil;
    
    self.fromEmail = nil;
    self.password = nil;
    self.subject = nil;
    self.relayHost = nil;
    self.toEmail = nil;
    [super dealloc];
}

- (id)init
{
    self = [super init];
    if(self)
    {
        _smtpMessage = [[SKPSMTPMessage alloc] init];
        _smtpMessage.wantsSecure = YES;
        _smtpMessage.delegate = self;
        _smtpMessage.requiresAuth = YES;
        
        _mailParts = [[NSMutableArray alloc] initWithCapacity:0];
        
        _filePathArray = [[NSMutableArray alloc] initWithCapacity:0];
        _dirPathArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return self;
}

#pragma mark -
#pragma mark 外部调用接口

- (void)setFromEmail:(NSString *)fromEmail
{
    if(_fromEmail != fromEmail)
    {
        [_fromEmail release];
        _fromEmail = [fromEmail retain];
        
        _smtpMessage.login = _fromEmail;
        _smtpMessage.fromEmail = _fromEmail;
    }
}

- (void)setPassword:(NSString *)password
{
    if(_password != password)
    {
        [_password release];
        _password = [password retain];
        
        _smtpMessage.pass = _password;
    }
}

- (void)setSubject:(NSString *)subject
{
    if(_subject != subject)
    {
        [_subject release];
        _subject = [subject retain];
        _smtpMessage.subject = _subject;
    }
}

- (void)setRelayHost:(NSString *)relayHost
{
    if(_relayHost != relayHost)
    {
        [_relayHost release];
        _relayHost = [relayHost retain];
        _smtpMessage.relayHost = _relayHost;
    }
}

- (void)setToEmail:(NSString *)toEmail
{
    if(_toEmail != toEmail)
    {
        [_toEmail release];
        _toEmail = [toEmail retain];
        
        _smtpMessage.toEmail = _toEmail;
    }
}

// 添加邮件正文内容
- (void)addMailContent:(NSString *)mailcontent
{
    mailcontent = (mailcontent == nil) ? @"" : mailcontent;
    
    NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/plain",kSKPSMTPPartContentTypeKey,
                               mailcontent,kSKPSMTPPartMessageKey,@"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
    
    [_mailParts addObject:plainPart];
}

// 添加附件，附件名称使用文件名，当文件超过10M,将不进行主动发送
- (BOOL)addAttachmentByFilePath:(NSString *)filePath
{
    if(![[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        return NO;
    }
    
    [_filePathArray addObject:filePath];
    
    NSString *fileName = [[NSFileManager defaultManager] displayNameAtPath:filePath];
    NSString *contentType = [[NSString alloc] initWithFormat:@"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"%@\"", fileName];
    NSString *contentDisposition = [[NSString alloc] initWithFormat:@"attachment;\r\n\tfilename=\"%@\"", fileName];
    
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    
    NSDictionary *filePart = [NSDictionary dictionaryWithObjectsAndKeys:contentType,kSKPSMTPPartContentTypeKey,
                             contentDisposition,kSKPSMTPPartContentDispositionKey,[fileData encodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
    [_mailParts addObject:filePart];
    
    [contentType release];
    [contentDisposition release];
    
    return YES;
}

// 将整个目录下的所有文件作为附件进行发送，当所有文件超过10M,将不进行主动发送
- (BOOL)addAttachmentsByDirPath:(NSString *)dirPath
{
    // 遍历目录
    NSArray *allFilePathArray = [self getAllFilePathBydirPath:dirPath];
    
    if(allFilePathArray == nil || [allFilePathArray count] == 0)
    {
        return NO;
    }
    
    [_dirPathArray addObject:dirPath];
    
    for(NSString *filePath in allFilePathArray)
    {
        [self addAttachmentByFilePath:filePath];
    }
    
    return YES;
}

// 所有操作完成之后，调用发送命令
- (void)sendMail
{
    _smtpMessage.parts = _mailParts;
    
    [_smtpMessage send];
}

#pragma mark -
#pragma mark 内部调用，功能性函数

// 获取dirPath路径下所有的文件路径
- (NSArray *)getAllFilePathBydirPath:(NSString *)dirPath
{
    if(![[NSFileManager defaultManager] fileExistsAtPath:dirPath])
    {
        NSLog(@"getAllFilePathBydirPath %@ not found", dirPath);
        return nil;
    }
    const char *dirName = [dirPath UTF8String];
    
    DIR *dirp = opendir(dirName);
    
    if(dirp == NULL)
    {
        NSLog(@"SendMailHandler::getAllFilePathBydirPath open dir:%@ error", dirPath);
        return nil;
    }
    
    NSMutableArray *allFileArray = [[NSMutableArray alloc] initWithCapacity:0];
    
    struct dirent *dp;
    while ((dp = readdir(dirp)) != NULL)
    {
        if (dp->d_name != NULL)
        {
            // 非目录
            if (dp->d_type != DT_DIR)
            {
                NSString *filePath = [[NSString alloc] initWithFormat:@"%@/%s", dirPath, dp->d_name];
                [allFileArray addObject:filePath];
                [filePath release];
            }
        }
    }
    if(dirp)
    {
        closedir(dirp);
        dirp = NULL;
    }
    return [allFileArray autorelease];
}

// 移除某个文件
- (BOOL)removeFileByPath:(NSString *)filePath
{
    NSError *err;
    BOOL isSuccess = [[NSFileManager defaultManager] removeItemAtPath:filePath error:&err];
    if(!isSuccess)
    {
        NSLog(@"removeFileByPath error, filePath:%@ err:%@", filePath, err);
    }
    return isSuccess;
}

// 移除目录中的所有文件
- (void)removeFileByDirPath:(NSString *)dirPath
{
    NSArray *allFileArray = [self getAllFilePathBydirPath:dirPath];
    for(NSString *filePath in allFileArray)
    {
        [self removeFileByPath:filePath];
    }
}

#pragma mark -
#pragma mark 代理实现函数
-(void)messageSent:(SKPSMTPMessage *)message
{
    NSLog(@"邮件发送成功");
    
    [_mailParts removeAllObjects];
    
    // 发送成功，删除crash log文件
    if(_filePathArray && [_filePathArray count] > 0)
    {
        for(NSString *filePath in _filePathArray)
        {
            [self removeFileByPath:filePath];
        }
        [_filePathArray removeAllObjects];
    }
    if(_dirPathArray && [_dirPathArray count] > 0)
    {
        for(NSString *dirPath in _dirPathArray)
        {
            [self removeFileByDirPath:dirPath];
        }
        [_dirPathArray removeAllObjects];
    }
    
    if(_messageDelegate)
    {
        [_messageDelegate messageSent:message];
    }
}

-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
    NSLog(@"邮件发送失败 error = %@", error);
    
//    [_mailParts removeAllObjects];
    
    if(_messageDelegate)
    {
        [_messageDelegate messageFailed:message error:error];
    }
}

@end
